package com.besall.allbase.view.activity.chipstoollevel4.ota;

import static com.bes.bessdk.BesSdkConstants.BES_BLE_OTA_AUTO_TEST;
import static com.bes.bessdk.BesSdkConstants.BES_BLE_OTA_AUTO_TEST_BIN_NAME_MARK;
import static com.bes.bessdk.BesSdkConstants.BES_BLE_OTA_AUTO_TEST_VALUE;
import static com.bes.bessdk.BesSdkConstants.BES_CONNECT_ERROR;
import static com.bes.bessdk.BesSdkConstants.BES_CONNECT_SUCCESS;
import static com.bes.bessdk.BesSdkConstants.BES_SAVE_LOG_OTA;
import static com.bes.bessdk.service.BesOTAConstants.BES_KEY_USE_INTERNAL_FILE_ACCESS;
import static com.bes.bessdk.service.BesOTAConstants.BES_KEY_USE_INTERNAL_FILE_ACCESS_CHOOSE_FILE;
import static com.bes.bessdk.service.BesOTAConstants.BES_OTA_IS_MULTIDEVICE_UPGRADE;
import static com.bes.bessdk.service.BesOTAConstants.BES_USE_INTERNAL_FILE_ACCESS;
import static com.bes.bessdk.service.BesOTAConstants.MSG_GET_PROTOCOL_VERSION_TIME_OUT;
import static com.bes.bessdk.service.BesOTAConstants.MSG_GET_RANDOMID_TIME_OUT;
import static com.bes.bessdk.service.BesOTAConstants.MSG_GET_UPGRATE_TYPE_TIME_OUT;
import static com.bes.bessdk.service.BesOTAConstants.MSG_GET_VERSION_TIME_OUT;
import static com.bes.bessdk.service.BesOTAConstants.OTA_CMD_BREAKPOINT_CHECK;
import static com.bes.bessdk.service.BesOTAConstants.OTA_CMD_BREAKPOINT_CHECK_80;
import static com.bes.bessdk.service.BesOTAConstants.OTA_CMD_CRC_CHECK_PACKAGE_ERROR;
import static com.bes.bessdk.service.BesOTAConstants.OTA_CMD_CRC_CHECK_PACKAGE_OK;
import static com.bes.bessdk.service.BesOTAConstants.OTA_CMD_DISCONNECT;
import static com.bes.bessdk.service.BesOTAConstants.OTA_CMD_GET_HW_INFO;
import static com.bes.bessdk.service.BesOTAConstants.OTA_CMD_GET_PROTOCOL_VERSION;
import static com.bes.bessdk.service.BesOTAConstants.OTA_CMD_IMAGE_OVER_CONFIRM_ERROR;
import static com.bes.bessdk.service.BesOTAConstants.OTA_CMD_ROLESWITCH_COMPLETE;
import static com.bes.bessdk.service.BesOTAConstants.OTA_CMD_ROLESWITCH_GET_RANDOMID;
import static com.bes.bessdk.service.BesOTAConstants.OTA_CMD_SELECT_SIDE_ERROR;
import static com.bes.bessdk.service.BesOTAConstants.OTA_CMD_SELECT_SIDE_OK;
import static com.bes.bessdk.service.BesOTAConstants.OTA_CMD_SEND_CONFIGURE_ERROR;
import static com.bes.bessdk.service.BesOTAConstants.OTA_CMD_SEND_CONFIGURE_OK;
import static com.bes.bessdk.service.BesOTAConstants.OTA_CMD_SET_OAT_USER_ERROR;
import static com.bes.bessdk.service.BesOTAConstants.OTA_CMD_SET_OAT_USER_OK;
import static com.bes.bessdk.service.BesOTAConstants.OTA_CMD_SET_UPGRADE_TYPE_FAST;
import static com.bes.bessdk.service.BesOTAConstants.OTA_CMD_SET_UPGRADE_TYPE_NORMAL;
import static com.bes.bessdk.service.BesOTAConstants.OTA_CMD_WHOLE_CRC_CHECK_ERROR;
import static com.bes.bessdk.service.BesOTAConstants.OTA_CMD_WHOLE_CRC_CHECK_OK;
import static com.bes.bessdk.service.BesOTAConstants.OTA_SEND_DATA_PROGRESS;
import static com.bes.bessdk.service.BesOTAConstants.OTA_START_DEVICE_LOW_BATTERY_ERROR;
import static com.bes.bessdk.service.BesOTAConstants.OTA_START_OTA_ERROR;
import static com.bes.bessdk.service.BesOTAConstants.USER_BTH;
import static com.bes.bessdk.service.BesOTAConstants.USER_DIFF_FILE;
import static com.bes.bessdk.service.BesOTAConstants.USER_MULTIPLE;
import static com.bes.bessdk.service.BesOTAConstants.USER_ZIP_FILEs;
import static com.bes.bessdk.service.customerdial.CustomerDialConstants.CUSTOMER_DIAL_GET_FLASH_ADDRESS_RESULT_FAIL;
import static com.bes.bessdk.service.customerdial.CustomerDialConstants.CUSTOMER_DIAL_LOG_INFO;
import static com.bes.bessdk.service.customerdial.CustomerDialConstants.CUSTOM_DIAL_COLORS;
import static com.bes.bessdk.service.customerdial.CustomerDialConstants.OP_TOTA_WRITE_FLASH_PROCESS;
import static com.bes.bessdk.service.customerdial.CustomerDialConstants.OP_TOTA_WRITE_FLASH_WHOLE_CHECK_RESULT_FAIL;
import static com.bes.bessdk.service.customerdial.CustomerDialConstants.OP_TOTA_WRITE_FLASH_WHOLE_CHECK_RESULT_OK;
import static com.besall.allbase.common.Constants.OTA_CHOOSE_FILE_PATH_RESULT;

import static bb.lanxing.util.CommonUtil.PACKAGE_INFO;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.bes.bessdk.BesSdkConstants;
import com.bes.bessdk.connect.BTService;
import com.bes.bessdk.scan.BtHeleper;
import com.bes.bessdk.service.base.BesServiceConfig;
import com.bes.bessdk.service.base.BesServiceListener;
import com.bes.bessdk.utils.ArrayUtil;
import com.bes.bessdk.utils.SPHelper;
import com.bes.sdk.device.HmDevice;
import com.bes.sdk.message.MsgStrAnalyzer;
import com.bes.sdk.ota.OTATask;
import com.bes.sdk.utils.DeviceProtocol;
import com.bes.sdk.utils.OTAStatus;
import com.besall.allbase.bluetooth.BluetoothConstants;
import com.besall.allbase.common.Constants;
import com.besall.allbase.common.utils.ActivityUtils;
import com.besall.allbase.common.utils.CircleProgressView;
import com.besall.allbase.common.utils.FileUtils;
import com.besall.allbase.view.activity.chipstoollevel4.customerdial.CustomerDialBean;
import com.besall.allbase.view.activity.chipstoollevel4.ota.filepathadapter.FilePathAdapter;
import com.besall.allbase.view.activity.tools.confirmdialog.ConfirmDialog;
import com.besall.allbase.view.activity.tools.confirmdialog.ConfirmDialoglistener;
import com.besall.allbase.view.base.BaseActivity;
import com.nbsp.materialfilepicker.ui.FilePickerActivity;

import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import bb.lanxing.R;
import bb.lanxing.network.BiCiCallback;
import bb.lanxing.network.MyHttpClient;
import okhttp3.Call;

public class OtaUIActivity extends BaseActivity<IOtaUIActivity, OtaUIPresenter> implements IOtaUIActivity, View.OnClickListener, BesServiceListener, OTATask.StatusListener {
	private static OtaUIActivity instance;
	private final int VIEW_OTAING_VIEW_TAG = 5555;
	private final int VIEW_OTAING_NAME_TAG = 6666;
	private final int VIEW_OTAING_PERCENT_TAG = 7777;
	private boolean isStartOta = false;
	private int breakPoint = 1;
	private int USER_FLAG;
	protected int download_ota_version_code = 0;
	protected int mOtaUpdateSuccStatus = 0;
	private static final String MARK_INIT = "MARK_INIT";
	private static final String MARK_GET_VERSION = "MARK_GET_VERSION";
	private static final String MARK_FAIL = "MARK_FAIL";
	private static final String MARK_SUCCESS = "MARK_SUCCESS";
	private String curTitle;
	private String current_device_version = null;
	private String download_ota_url = null;
	private String download_ota_file_path = null;
	private String download_ota_version;
	protected String download_ota_soft_name = null;
	private BluetoothLeScanner mLeScanner;
	private BesServiceConfig mServiceConfig;
	private DeviceProtocol mDeviceProtocol;
	private List<HmDevice> mHmDevices;
	private List<String> mResults;
	private List<String> mFilePaths;
	private List<Integer> mProgresses;
	private OtaConfigFragment mOtaConfigDialog;
	private ImageView act_otaui_bg;
	private View view_device;
	private View view_baseoption;
	private View view_versionpath;
	private View view_button;
	private View view_otaing;
	private View view_otalog;
	private TextView device_title;
	private TextView device_name;
	private EditText device_version;
	private EditText get_server_ota_version;
	private View view_ack;
	protected View view_user;
	private View view_response;
	protected View view_upgradetype;
	private Button ack_btn_0;
	private ImageView ack_image_0;
	private Button ack_btn_1;
	private ImageView ack_image_1;
	private Button user_btn_0;
	private ImageView user_image_0;
	private Button user_btn_1;
	private ImageView user_image_1;
	private Button user_btn_2;
	private ImageView user_image_2;
	private Button user_btn_3;
	private ImageView user_image_3;
	private Button response_btn_0;
	private Button user_btn_4;
	private ImageView user_image_4;
	private Button user_btn_5;
	private ImageView user_image_5;
	private Button user_btn_6;
	private ImageView user_image_6;
	private Button user_btn_7;
	private ImageView user_image_7;
	private ImageView response_image_0;
	private Button response_btn_1;
	private ImageView response_image_1;
	private Button upgradetype_btn_0;
	private ImageView upgradetype_image_0;
	private Button upgradetype_btn_1;
	private ImageView upgradetype_image_1;
	private Button choose_device;
	private Button connect_device;
	protected View view_device_support;
	protected View view_device_bg;
	private Button ota_check_btn;
	private Button ota_file_tips_btn;
	private Button choose_file;
	private ListView file_path;
	private FilePathAdapter mAdapter;
	private ScrollView ota_log_scrollview;
	private TextView ota_log_text;
	private ScrollView ota_log_scrollview_short;
	private TextView ota_log_text_short;
	private Button ota_over_btn;
	private CircleProgressView mTasksView;
	private View view_otaing_bg;
	private View view_otaover_bg;
	private ImageView view_otaover_image;
	private TextView view_otaover_text;
	private View bgview0;
	private TextView text_name0;
	private TextView text_percent0;
	private View bgview1;
	private TextView text_name1;
	private TextView text_percent1;
	private View base_view1;
	private View text_view_0;
	private TextView text_name_0;
	private TextView text_percent_0;
	private View text_view_1;
	private TextView text_name_1;
	private TextView text_percent_1;
	private View text_view_2;
	private TextView text_name_2;
	private TextView text_percent_2;
	private View text_view_3;
	private TextView text_name_3;
	private TextView text_percent_3;
	private View text_view_4;
	private TextView text_name_4;
	private TextView text_percent_4;
	private View base_view2;
	private View text_view_5;
	private TextView text_name_5;
	private TextView text_percent_5;
	private View text_view_6;
	private TextView text_name_6;
	private TextView text_percent_6;
	private View text_view_7;
	private TextView text_name_7;
	private TextView text_percent_7;
	private View text_view_8;
	private TextView text_name_8;
	private TextView text_percent_8;
	private View text_view_9;
	private TextView text_name_9;
	private TextView text_percent_9;
	private Handler mainHandler = new Handler(Looper.getMainLooper());
	private BiCiCallback ota_get_version_info_callback = new BiCiCallback() {
		@Override public void onResponseString(@NonNull String str) {
			bb.lanxing.util.Log.d("ota_get_version_info_callback", "onResponseString: " + str);
			try {
				JSONObject object = new JSONObject(str);
				int code = object.getInt("code");
				int msgId = object.getInt("msgId");
				String msg = object.getString("msg");
				bb.lanxing.util.Log.d("ota_get_version_info_callback", "msgId:" + msgId);
				if (msgId == 0) {
					JSONObject dataObject = object.getJSONObject("data");
					download_ota_version = dataObject.getString("verName");
					download_ota_version_code = dataObject.getInt("verNum");
					download_ota_url = dataObject.getString("downloadUrl");
					download_ota_soft_name = dataObject.getString("softName");
					get_server_ota_version.setText(download_ota_version);
					if (download_ota_url != null) {
						// downloadOtaNewVersion();
						ota_check_btn.setText(R.string.ota_download);
					}
				} else {
					download_ota_url = null;
					get_server_ota_version.setText(msg);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		@Override public void onFailure(Call call, @NonNull IOException iOException) {
			bb.lanxing.util.Log.d("ota_get_version_info_callback", "onFailure: ");
		}
	};

	private OtaConfigFragment.OtaConfigCallback mOtaConfigCallback = new OtaConfigFragment.OtaConfigCallback() {
		@Override public void onOtaConfigOk() {
			mPresenter.startOta(instance, breakPoint, 0);
		}

		@Override public void onOtaConfigCancel() {
			mPresenter.stopOta();
			refreshUI(R.string.cancel);
		}
	};

	private BiCiCallback ota_download_new_version_callback = new BiCiCallback() {
		@Override public void onResponse(okhttp3.Response response) {
			bb.lanxing.util.Log.d("ota_download_new_version_callback", "onResponse: ");
			if (response.isSuccessful()) {
				download_ota_file_path = new FileUtils(instance).getOtaFilePath() + "/" + download_ota_version + ".bin";
				writeFile(response, download_ota_file_path);
				mainHandler.post(new Runnable() {
					@Override public void run() {
						download_ota_url = null;
						ota_check_btn.setText(R.string.get_new_version);
						ota_check_btn.setEnabled(true);
						onPickServerFile();
					}
				});
				// onPickServerFile();
			}
		}

		@Override public void onFailure(Call call, @NonNull IOException iOException) {
			bb.lanxing.util.Log.d("ota_download_new_version_callback", "onFailure: ");
		}

		@Override public void onResponseString(@NonNull String str) {
			bb.lanxing.util.Log.d("ota_download_new_version_callback", "onResponseString: " + str);
		}
	};

	private static void deleteAllFilesInDirectory(String directoryPath) {
		File directory = new File(directoryPath);
		if (directory.exists() && directory.isDirectory()) {
			File[] files = directory.listFiles(new FilenameFilter() {
				@Override public boolean accept(File dir, String name) {
					return true;
				}
			});
			if (files != null) {
				for (File file : files) {
					if (file.delete()) {
						System.out.println("Deleted file: " + file.getName());
					} else {
						System.out.println("Failed to delete file: " + file.getName());
					}
				}
			}
		}
	}

	@Override public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == android.R.id.home) {
			if (view_otaing.getVisibility() == View.VISIBLE) {
				showConfirmDialog(getString(R.string.ota_exit_tips));
				return false;
			}
			finish();
		} else if (item.getItemId() == R.id.menu_setting) {
			mPresenter.goToSettingActivity(instance);
		}
		return super.onOptionsItemSelected(item);
	}

	@Override protected OtaUIPresenter createPresenter() {
		return new OtaUIPresenter();
	}

	private void initTitleStr() {
		String titleProtocolStr = "";
		if (mDeviceProtocol == DeviceProtocol.PROTOCOL_BLE) {
			titleProtocolStr = "BLE";
		} else if (mDeviceProtocol == DeviceProtocol.PROTOCOL_SPP) {
			titleProtocolStr = "SPP";
		} else if (mDeviceProtocol == DeviceProtocol.PROTOCOL_GATT_BR_EDR) {
			titleProtocolStr = "GATT OVER BR/EDR";
		} else if (mDeviceProtocol == DeviceProtocol.PROTOCOL_USB) {
			titleProtocolStr = "USB";
		}
		String titleDisplayStr = "";
		if (USER_FLAG == -1) {
			titleDisplayStr = titleProtocolStr + (mServiceConfig.getTotaConnect() ? " TOTA" : "") + " OTA Old Service 1.0";
		} else if (USER_FLAG == 0) {
			titleDisplayStr = titleProtocolStr + (mServiceConfig.getTotaConnect() ? " TOTA" : "") + " OTA 1.0";
		} else if (USER_FLAG == 1) {
			titleDisplayStr = titleProtocolStr + (mServiceConfig.getTotaConnect() ? " TOTA" : "") + " OTA 2.0";
		}
		curTitle = getString(R.string.lanxing_ota);
		//curTitle = titleDisplayStr;
		SPHelper.putPreference(instance, BesSdkConstants.BES_SAVE_LOG_NAME, curTitle);
	}

	@Override protected void initBeforeSetContent() {
		mServiceConfig = (BesServiceConfig) getIntent().getSerializableExtra(Constants.OTA_SERVICE_CONFIG);
		USER_FLAG = mServiceConfig.getUSER_FLAG();
		mDeviceProtocol = mServiceConfig.getDeviceProtocol();
		initTitleStr();
		LOG(TAG, "initBeforeSetContent");
		initResults();
		initFilePaths("");
	}

	private void initResults() {
		mResults = new ArrayList<>();
		mProgresses = new ArrayList<>();
		for (int i = 0; i < 10; i++) {
			mResults.add(MARK_INIT);
			mProgresses.add(0);
		}
	}

	private void initFilePaths(String path) {
		mFilePaths = new ArrayList<>();
		for (int i = 0; i < 10; i++) {
			mFilePaths.add(path);
		}
		// init bin path
		new FileUtils(instance).initBinFile();
	}

	private CurResultsState checkCurResults() {
		ArrayList<String> results = new ArrayList<>();
		for (int i = 0; i < mHmDevices.size(); i++) {
			results.add(mResults.get(i));
		}
		if (!results.contains(MARK_SUCCESS) && !results.contains(MARK_FAIL)) {
			return CurResultsState.BES_UPGRADING;
		} else if (results.contains(MARK_INIT) && results.contains(MARK_FAIL)) {
			return CurResultsState.BES_UPGRADING_HAS_FAIL;
		} else if (!results.contains(MARK_INIT) && results.contains(MARK_FAIL) && results.contains(MARK_SUCCESS)) {
			return CurResultsState.BES_OVER_HAS_FAIL;
		} else if (!results.contains(MARK_INIT) && !results.contains(MARK_FAIL)) {
			return CurResultsState.BES_OVER_ALL_SUCCESS;
		} else if (!results.contains(MARK_INIT) && !results.contains(MARK_SUCCESS)) {
			return CurResultsState.BES_OVER_ALL_FAIL;
		}
		return CurResultsState.BES_UPGRADING;
	}

	@Override protected int getContentViewId() {
		return R.layout.act_otaui;
	}

	@Override protected void bindView() {
		act_otaui_bg = (ImageView) findViewById(R.id.act_otaui_bg);
		view_device = (View) findViewById(R.id.view_device);
		view_baseoption = (View) findViewById(R.id.view_baseoption);
		view_versionpath = (View) findViewById(R.id.view_versionpath);
		view_button = (View) findViewById(R.id.view_button);
		view_otaing = (View) findViewById(R.id.view_otaing);
		view_otalog = (View) findViewById(R.id.view_otalog);
		device_title = (TextView) findViewById(R.id.device_title);
		device_name = (TextView) findViewById(R.id.device_name);
		device_version = (EditText) findViewById(R.id.device_version);
		get_server_ota_version = (EditText) findViewById(R.id.get_server_ota_version);
		view_ack = (View) findViewById(R.id.view_ack);
		view_user = (View) findViewById(R.id.view_user);
		view_response = (View) findViewById(R.id.view_response);
		view_upgradetype = (View) findViewById(R.id.view_upgradetype);
		ack_btn_0 = (Button) findViewById(R.id.ack_btn_0);
		ack_image_0 = (ImageView) findViewById(R.id.ack_image_0);
		ack_btn_1 = (Button) findViewById(R.id.ack_btn_1);
		ack_image_1 = (ImageView) findViewById(R.id.ack_image_1);
		user_btn_0 = (Button) findViewById(R.id.user_btn_0);
		user_image_0 = (ImageView) findViewById(R.id.user_image_0);
		user_btn_1 = (Button) findViewById(R.id.user_btn_1);
		user_image_1 = (ImageView) findViewById(R.id.user_image_1);
		user_btn_2 = (Button) findViewById(R.id.user_btn_2);
		user_image_2 = (ImageView) findViewById(R.id.user_image_2);
		user_btn_3 = (Button) findViewById(R.id.user_btn_3);
		user_image_3 = (ImageView) findViewById(R.id.user_image_3);
		user_btn_4 = (Button) findViewById(R.id.user_btn_4);
		user_image_4 = (ImageView) findViewById(R.id.user_image_4);
		user_btn_5 = (Button) findViewById(R.id.user_btn_5);
		user_image_5 = (ImageView) findViewById(R.id.user_image_5);
		user_btn_6 = (Button) findViewById(R.id.user_btn_6);
		user_image_6 = (ImageView) findViewById(R.id.user_image_6);
		user_btn_7 = (Button) findViewById(R.id.user_btn_7);
		user_image_7 = (ImageView) findViewById(R.id.user_image_7);
		response_btn_0 = (Button) findViewById(R.id.response_btn_0);
		response_image_0 = (ImageView) findViewById(R.id.response_image_0);
		response_btn_1 = (Button) findViewById(R.id.response_btn_1);
		response_image_1 = (ImageView) findViewById(R.id.response_image_1);
		upgradetype_btn_0 = (Button) findViewById(R.id.upgradetype_btn_0);
		upgradetype_image_0 = (ImageView) findViewById(R.id.upgradetype_image_0);
		upgradetype_btn_1 = (Button) findViewById(R.id.upgradetype_btn_1);
		upgradetype_image_1 = (ImageView) findViewById(R.id.upgradetype_image_1);
		choose_device = (Button) findViewById(R.id.choose_device);
		connect_device = (Button) findViewById(R.id.connect_device);
		view_device_support = (View) findViewById(R.id.view_device_support);
		view_device_bg = (View) findViewById(R.id.view_device_bg);

		ota_file_tips_btn = (Button) findViewById(R.id.ota_file_tips_btn);
		choose_file = (Button) findViewById(R.id.choose_file);
		mAdapter = new FilePathAdapter(instance, instance);
		file_path = (ListView) findViewById(R.id.file_path);
		file_path.setAdapter(mAdapter);
		ota_log_scrollview = (ScrollView) findViewById(R.id.ota_log_scrollview);
		ota_log_text = (TextView) findViewById(R.id.ota_log_text);
		ota_log_scrollview_short = (ScrollView) findViewById(R.id.ota_log_scrollview_short);
		ota_log_text_short = (TextView) findViewById(R.id.ota_log_text_short);
		ota_over_btn = (Button) findViewById(R.id.ota_over_btn);
		mTasksView = (CircleProgressView) findViewById(R.id.tasks_view);
		view_otaing_bg = (View) findViewById(R.id.view_otaing_bg);
		view_otaover_bg = (View) findViewById(R.id.view_otaover_bg);
		view_otaover_image = (ImageView) findViewById(R.id.view_otaover_image);
		view_otaover_text = (TextView) findViewById(R.id.view_otaover_text);
		ota_check_btn = (Button) findViewById(R.id.ota_check_btn);
	}

	@SuppressLint("ResourceAsColor") @Override protected void initView() {
		LOG(TAG, "initView");
		inittoolbar(curTitle);
		String hDecviceName = (String) SPHelper.getPreference(instance, Constants.OTA_HISTOTY_DEVICE_NAME + curTitle, "--");
		device_name.setText(hDecviceName);
		ack_btn_0.setOnClickListener(instance);
		ack_btn_1.setOnClickListener(instance);
		user_btn_0.setOnClickListener(instance);
		user_btn_1.setOnClickListener(instance);
		user_btn_2.setOnClickListener(instance);
		user_btn_3.setOnClickListener(instance);
		user_btn_4.setOnClickListener(instance);
		user_btn_5.setOnClickListener(instance);
		user_btn_6.setOnClickListener(instance);
		user_btn_7.setOnClickListener(instance);
		response_btn_0.setOnClickListener(instance);
		response_btn_1.setOnClickListener(instance);
		upgradetype_btn_0.setOnClickListener(instance);
		upgradetype_btn_1.setOnClickListener(instance);

		ack_image_0.setImageResource(R.drawable.ota_top_nor);
		ack_image_1.setImageDrawable(getDrawable(R.drawable.ota_top_nor));
		user_image_0.setImageResource(R.drawable.ota_top_nor);
		user_image_1.setImageDrawable(getDrawable(R.drawable.ota_top_nor));
		user_image_2.setImageDrawable(getDrawable(R.drawable.ota_top_nor));
		user_image_3.setImageDrawable(getDrawable(R.drawable.ota_top_nor));
		user_image_4.setImageDrawable(getDrawable(R.drawable.ota_top_nor));
		user_image_5.setImageDrawable(getDrawable(R.drawable.ota_top_nor));
		user_image_6.setImageDrawable(getDrawable(R.drawable.ota_top_nor));
		user_image_7.setImageDrawable(getDrawable(R.drawable.ota_top_nor));

		response_image_0.setImageResource(R.drawable.ota_top_nor);
		response_image_1.setImageDrawable(getDrawable(R.drawable.ota_top_nor));
		upgradetype_image_0.setImageResource(R.drawable.ota_top_nor);
		upgradetype_image_1.setImageDrawable(getDrawable(R.drawable.ota_top_nor));

		boolean ackStyle = (boolean) SPHelper.getPreference(instance, Constants.OTA_ACK_STYLE + curTitle, false);
		if (ackStyle) {
			ack_image_1.setImageDrawable(getDrawable(R.drawable.ota_top_sele));
			response_image_1.setImageDrawable(getDrawable(R.drawable.ota_top_sele));
		} else {
			ack_image_0.setImageDrawable(getDrawable(R.drawable.ota_top_sele));
			response_image_0.setImageDrawable(getDrawable(R.drawable.ota_top_sele));
		}
		if (mServiceConfig.getCurUser() != null) {
			SPHelper.putPreference(instance, Constants.OTA_USER_TYPE + curTitle, mServiceConfig.getCurUser());
		}
		int userType = (int) SPHelper.getPreference(instance, Constants.OTA_USER_TYPE + curTitle, 1);
		if (userType == 1) {
			user_image_0.setImageResource(R.drawable.ota_top_sele);
		} else if (userType == 2) {
			user_image_1.setImageResource(R.drawable.ota_top_sele);
		} else if (userType == 3) {
			user_image_2.setImageResource(R.drawable.ota_top_sele);
		} else if (userType == 4) {
			user_image_3.setImageResource(R.drawable.ota_top_sele);
		} else if (userType == USER_MULTIPLE) {
			user_image_4.setImageResource(R.drawable.ota_top_sele);
		} else if (userType == USER_BTH) {
			user_image_5.setImageResource(R.drawable.ota_top_sele);
		} else if (userType == USER_DIFF_FILE) {
			user_image_6.setImageResource(R.drawable.ota_top_sele);
		} else if (userType == USER_ZIP_FILEs) {
			user_image_7.setImageResource(R.drawable.ota_top_sele);
		}
		int upgradeType = (int) SPHelper.getPreference(instance, Constants.OTA_UPGRADE_STYLE + curTitle, 1);
		if (upgradeType == 1) {
			upgradetype_image_0.setImageResource(R.drawable.ota_top_sele);
		} else if (upgradeType == 2) {
			upgradetype_image_1.setImageResource(R.drawable.ota_top_sele);
		}
		if (USER_FLAG == 0) {
			view_response.setVisibility(View.GONE);
		} else if (USER_FLAG == 1) {
			view_ack.setVisibility(View.GONE);
		}
		choose_device.setOnClickListener(instance);
		connect_device.setOnClickListener(instance);
		ota_file_tips_btn.setOnClickListener(instance);
		choose_file.setOnClickListener(instance);
		ota_over_btn.setOnClickListener(instance);
		ota_check_btn.setOnClickListener(instance);
		mOtaConfigDialog = new OtaConfigFragment();
		mOtaConfigDialog.setOtaConfigCallback(mOtaConfigCallback);
		loadanimdrawable();
		if (mServiceConfig.getDevice() != null) {
			mHmDevices = new ArrayList<>();
			mHmDevices.add(mServiceConfig.getDevice());
			device_title.setText(R.string.current_device);
			device_name.setText(getCurDevicesName());
			if (mServiceConfig.getUSER_FLAG() == -1) {
				initResults();
				connect();
			} else if (mServiceConfig.getUSER_FLAG() == 1 && mHmDevices.size() == 1) {
				view_baseoption.setVisibility(View.GONE);
				act_otaui_bg.setBackground(getResources().getDrawable(R.mipmap.bes_bg_white));
				view_versionpath.setVisibility(View.VISIBLE);
				choose_device.setVisibility(View.INVISIBLE);
				connect_device.setText(R.string.start_ota);
				connect();
			}
		}
	}

	private void initOtaingView() {
		int size = mHmDevices.size();
		bb.lanxing.util.Log.i("initOtaingView size = " + size);
		if (mHmDevices.size() == 1) {
			text_name0 = (TextView) findViewById(R.id.text_name0);
			text_percent0 = (TextView) findViewById(R.id.text_percent0);
		} else if (mHmDevices.size() == 2) {
			text_name0 = (TextView) findViewById(R.id.text_name0);
			text_percent0 = (TextView) findViewById(R.id.text_percent0);
			bgview1 = (View) findViewById(R.id.bgview1);
			bgview1.setVisibility(View.VISIBLE);
			text_name1 = (TextView) findViewById(R.id.text_name1);
			text_percent1 = (TextView) findViewById(R.id.text_percent1);
		} else {
			bgview0 = (View) findViewById(R.id.bgview0);
			bgview0.setVisibility(View.GONE);
			bgview1 = (View) findViewById(R.id.bgview1);
			bgview1.setVisibility(View.GONE);

			base_view1 = (View) findViewById(R.id.base_view1);
			base_view1.setVisibility(View.VISIBLE);
			text_view_0 = (View) findViewById(R.id.text_view_0);
			text_view_0.setTag(VIEW_OTAING_VIEW_TAG + 0);
			text_name_0 = (TextView) findViewById(R.id.text_name_0);
			text_name_0.setTag(VIEW_OTAING_NAME_TAG + 0);
			text_percent_0 = (TextView) findViewById(R.id.text_percent_0);
			text_percent_0.setTag(VIEW_OTAING_PERCENT_TAG + 0);

			text_view_1 = (View) findViewById(R.id.text_view_1);
			text_view_1.setTag(VIEW_OTAING_VIEW_TAG + 1);
			text_name_1 = (TextView) findViewById(R.id.text_name_1);
			text_name_1.setTag(VIEW_OTAING_NAME_TAG + 1);
			text_percent_1 = (TextView) findViewById(R.id.text_percent_1);
			text_percent_1.setTag(VIEW_OTAING_PERCENT_TAG + 1);

			text_view_2 = (View) findViewById(R.id.text_view_2);
			text_view_2.setTag(VIEW_OTAING_VIEW_TAG + 2);
			text_name_2 = (TextView) findViewById(R.id.text_name_2);
			text_name_2.setTag(VIEW_OTAING_NAME_TAG + 2);
			text_percent_2 = (TextView) findViewById(R.id.text_percent_2);
			text_percent_2.setTag(VIEW_OTAING_PERCENT_TAG + 2);

			text_view_3 = (View) findViewById(R.id.text_view_3);
			text_view_3.setTag(VIEW_OTAING_VIEW_TAG + 3);
			text_name_3 = (TextView) findViewById(R.id.text_name_3);
			text_name_3.setTag(VIEW_OTAING_NAME_TAG + 3);
			text_percent_3 = (TextView) findViewById(R.id.text_percent_3);
			text_percent_3.setTag(VIEW_OTAING_PERCENT_TAG + 3);

			text_view_4 = (View) findViewById(R.id.text_view_4);
			text_view_4.setTag(VIEW_OTAING_VIEW_TAG + 4);
			text_name_4 = (TextView) findViewById(R.id.text_name_4);
			text_name_4.setTag(VIEW_OTAING_NAME_TAG + 4);
			text_percent_4 = (TextView) findViewById(R.id.text_percent_4);
			text_percent_4.setTag(VIEW_OTAING_PERCENT_TAG + 4);

			if (mHmDevices.size() < 6) {
				for (int i = 0; i < mHmDevices.size(); i++) {
					View textView = (View) base_view1.findViewWithTag(VIEW_OTAING_VIEW_TAG + i);
					textView.setVisibility(View.VISIBLE);
				}
				return;
			}
			base_view2 = (View) findViewById(R.id.base_view2);
			base_view2.setVisibility(View.VISIBLE);
			text_view_5 = (View) findViewById(R.id.text_view_5);
			text_view_5.setTag(VIEW_OTAING_VIEW_TAG + 5);
			text_name_5 = (TextView) findViewById(R.id.text_name_5);
			text_name_5.setTag(VIEW_OTAING_NAME_TAG + 5);
			text_percent_5 = (TextView) findViewById(R.id.text_percent_5);
			text_percent_5.setTag(VIEW_OTAING_PERCENT_TAG + 5);

			text_view_6 = (View) findViewById(R.id.text_view_6);
			text_view_6.setTag(VIEW_OTAING_VIEW_TAG + 6);
			text_name_6 = (TextView) findViewById(R.id.text_name_6);
			text_name_6.setTag(VIEW_OTAING_NAME_TAG + 6);
			text_percent_6 = (TextView) findViewById(R.id.text_percent_6);
			text_percent_6.setTag(VIEW_OTAING_PERCENT_TAG + 6);

			text_view_7 = (View) findViewById(R.id.text_view_7);
			text_view_7.setTag(VIEW_OTAING_VIEW_TAG + 7);
			text_name_7 = (TextView) findViewById(R.id.text_name_7);
			text_name_7.setTag(VIEW_OTAING_NAME_TAG + 7);
			text_percent_7 = (TextView) findViewById(R.id.text_percent_7);
			text_percent_7.setTag(VIEW_OTAING_PERCENT_TAG + 7);

			text_view_8 = (View) findViewById(R.id.text_view_8);
			text_view_8.setTag(VIEW_OTAING_VIEW_TAG + 8);
			text_name_8 = (TextView) findViewById(R.id.text_name_8);
			text_name_8.setTag(VIEW_OTAING_NAME_TAG + 8);
			text_percent_8 = (TextView) findViewById(R.id.text_percent_8);
			text_percent_8.setTag(VIEW_OTAING_PERCENT_TAG + 8);

			text_view_9 = (View) findViewById(R.id.text_view_9);
			text_view_9.setTag(VIEW_OTAING_VIEW_TAG + 9);
			text_name_9 = (TextView) findViewById(R.id.text_name_9);
			text_name_9.setTag(VIEW_OTAING_NAME_TAG + 9);
			text_percent_9 = (TextView) findViewById(R.id.text_percent_9);
			text_percent_9.setTag(VIEW_OTAING_PERCENT_TAG + 9);

			for (int i = 0; i < mHmDevices.size(); i++) {
				View textView = i < 5 ? (View) base_view1.findViewWithTag(VIEW_OTAING_VIEW_TAG + i) : (View) base_view2.findViewWithTag(VIEW_OTAING_VIEW_TAG + i);
				textView.setVisibility(View.VISIBLE);
			}
		}
	}

	private void reloadOtaingView(String name, String percent, int index) {
		int size = mHmDevices.size();
		bb.lanxing.util.Log.i("reloadOtaingView size = " + size + ",index = " + index + ",percent = " + percent);
		if (mHmDevices.size() == 1 || (mHmDevices.size() == 2 && index == 0)) {
			text_name0.setText(name);
			text_percent0.setText(getString(R.string.string_format, percent));
		} else if (mHmDevices.size() == 2 && index == 1) {
			text_name1.setText(name);
			text_percent1.setText(getString(R.string.string_format, percent));
		} else if (index < 10) {
			View textView = index < 5 ? (View) base_view1.findViewWithTag(VIEW_OTAING_VIEW_TAG + index) : (View) base_view2.findViewWithTag(VIEW_OTAING_VIEW_TAG + index);
			TextView text_name = (TextView) textView.findViewWithTag(VIEW_OTAING_NAME_TAG + index);
			text_name.setText(name);
			TextView text_percent = (TextView) textView.findViewWithTag(VIEW_OTAING_PERCENT_TAG + index);
			text_percent.setText(getString(R.string.string_format, percent));
		}
	}

	private void reloadOtaingTextColor(int index, boolean isSuccess) {
		if (mHmDevices.size() == 1 || (mHmDevices.size() == 2 && index == 0)) {
			if (text_percent0 != null) {
				text_percent0.setTextColor(isSuccess ? getResources().getColor(R.color.green) : Color.RED);
			}
		} else if (mHmDevices.size() == 2 && index == 1) {
			if (text_percent1 != null) {
				text_percent1.setTextColor(isSuccess ? getResources().getColor(R.color.green) : Color.RED);
			}
		} else if (index < 10) {
			if (base_view1 != null) {
				View textView = index < 5 ? (View) base_view1.findViewWithTag(VIEW_OTAING_VIEW_TAG + index) : (View) base_view2.findViewWithTag(VIEW_OTAING_VIEW_TAG + index);
				if (textView != null) {
					TextView text_percent = (TextView) textView.findViewWithTag(VIEW_OTAING_PERCENT_TAG + index);
					text_percent.setTextColor(isSuccess ? getResources().getColor(R.color.green) : Color.RED);
				}
			}
		}
	}

	private void showConfirmDialog(String msg) {
		ConfirmDialog confirmDialog = new ConfirmDialog(instance, msg, new ConfirmDialoglistener() {
			@Override public void confirmYes() {
				finish();
			}

			@Override public void confirmNo() {
			}
		});

		runOnUiThread(() -> confirmDialog.show());
	}

	private void showOtaFileTipsDialog(String msg) {
		ConfirmDialog confirmDialog = new ConfirmDialog(instance, msg, new ConfirmDialoglistener() {
			@Override public void confirmYes() {
				SPHelper.putPreference(instance, BES_KEY_USE_INTERNAL_FILE_ACCESS, true);
				chooseFile();
			}

			@Override public void confirmNo() {
				SPHelper.putPreference(instance, BES_KEY_USE_INTERNAL_FILE_ACCESS, false);
			}
		});

		runOnUiThread(() -> confirmDialog.show());
	}

	@Override public boolean onCreateOptionsMenu(Menu menu) {
		// getMenuInflater().inflate(R.menu.menu_setting, menu);
		return true;
	}

	@Override protected void setInstance() {
		instance = this;
	}

	@Override protected void removeInstance() {
		instance = null;
	}

	@Override public void onClick(View v) {
		LOG(TAG, "onClick");
		if (v.getId() == R.id.ack_btn_0) {
			resetAckView();
			ack_image_0.setImageDrawable(getDrawable(R.drawable.ota_top_sele));
			SPHelper.putPreference(getApplicationContext(), Constants.OTA_ACK_STYLE + curTitle, false);
		} else if (v.getId() == R.id.ack_btn_1) {
			resetAckView();
			ack_image_1.setImageDrawable(getDrawable(R.drawable.ota_top_sele));
			SPHelper.putPreference(getApplicationContext(), Constants.OTA_ACK_STYLE + curTitle, true);
		} else if (v.getId() == R.id.user_btn_0) {
			resetUserView();
			user_image_0.setImageDrawable(getDrawable(R.drawable.ota_top_sele));
			SPHelper.putPreference(getApplicationContext(), Constants.OTA_USER_TYPE + curTitle, 1);
		} else if (v.getId() == R.id.user_btn_1) {
			resetUserView();
			user_image_1.setImageDrawable(getDrawable(R.drawable.ota_top_sele));
			SPHelper.putPreference(getApplicationContext(), Constants.OTA_USER_TYPE + curTitle, 2);
		} else if (v.getId() == R.id.user_btn_2) {
			resetUserView();
			user_image_2.setImageDrawable(getDrawable(R.drawable.ota_top_sele));
			SPHelper.putPreference(getApplicationContext(), Constants.OTA_USER_TYPE + curTitle, 3);
		} else if (v.getId() == R.id.user_btn_3) {
			resetUserView();
			user_image_3.setImageDrawable(getDrawable(R.drawable.ota_top_sele));
			SPHelper.putPreference(getApplicationContext(), Constants.OTA_USER_TYPE + curTitle, 4);
		} else if (v.getId() == R.id.user_btn_4) {
			resetUserView();
			user_image_4.setImageDrawable(getDrawable(R.drawable.ota_top_sele));
			SPHelper.putPreference(getApplicationContext(), Constants.OTA_USER_TYPE + curTitle, USER_MULTIPLE);
		} else if (v.getId() == R.id.user_btn_5) {
			resetUserView();
			user_image_5.setImageDrawable(getDrawable(R.drawable.ota_top_sele));
			SPHelper.putPreference(getApplicationContext(), Constants.OTA_USER_TYPE + curTitle, USER_BTH);
			// resetUserView();
			// user_image_5.setImageDrawable(getDrawable(R.drawable.ota_top_sele));
			// SPHelper.putPreference(getApplicationContext(),Constants.OTA_USER_TYPE + curTitle, USER_BTH);
		} else if (v.getId() == R.id.user_btn_6) {
			resetUserView();
			user_image_6.setImageDrawable(getDrawable(R.drawable.ota_top_sele));
			SPHelper.putPreference(getApplicationContext(), Constants.OTA_USER_TYPE + curTitle, USER_DIFF_FILE);
		} else if (v.getId() == R.id.user_btn_7) {
			resetUserView();
			user_image_7.setImageDrawable(getDrawable(R.drawable.ota_top_sele));
			SPHelper.putPreference(getApplicationContext(), Constants.OTA_USER_TYPE + curTitle, USER_ZIP_FILEs);
		} else if (v.getId() == R.id.response_btn_0) {
			// the comment out is from bes ota fast 0613version code
			/*
			 * resetResponseView(); response_image_0.setImageDrawable(getDrawable(R.drawable.ota_top_sele));
			 * SPHelper.putPreference(getApplicationContext(),Constants.OTA_ACK_STYLE + curTitle,false);
			 */
			isStartOta = false;
			// resetResponseView();
			// response_image_0.setImageDrawable(getDrawable(R.drawable.ota_top_sele));
			// SPHelper.putPreference(getApplicationContext(),Constants.OTA_ACK_STYLE + curTitle,false);
			BesServiceConfig customerDialConfig = new BesServiceConfig();
			customerDialConfig.setServiceUUID(BesSdkConstants.BES_SPP_CONNECT);
			customerDialConfig.setUseTotaV2(true);
			customerDialConfig.setTotaConnect(true);
			customerDialConfig.setDeviceProtocol(DeviceProtocol.PROTOCOL_SPP);
			customerDialConfig.setDevice(mHmDevices.get(0));
			mPresenter.connectCustomerDialDevice(customerDialConfig, instance, instance);
		} else if (v.getId() == R.id.response_btn_1) {
			// the comment out is from bes ota fast 0613version code
			/*
			 * resetResponseView(); response_image_1.setImageDrawable(getDrawable(R.drawable.ota_top_sele));
			 * SPHelper.putPreference(getApplicationContext(),Constants.OTA_ACK_STYLE + curTitle,true);
			 */

			isStartOta = false;
			// resetResponseView();
			// response_image_1.setImageDrawable(getDrawable(R.drawable.ota_top_sele));
			// SPHelper.putPreference(getApplicationContext(),Constants.OTA_ACK_STYLE + curTitle,true);
			Log.i(TAG, "onClick: ---------response_btn_1");
			CustomerDialBean curDialBean = new CustomerDialBean();
			curDialBean.setStyle(1);
			curDialBean.setColor(2);
			byte[] type = ArrayUtil.intToBytesLittle(curDialBean.getStyle());
			byte[] color = ArrayUtil.toBytes(CUSTOM_DIAL_COLORS[curDialBean.getColor() < 0 ? 0 : curDialBean.getColor()].replace("#", ""));
			byte[] param = new byte[] { type[0], type[1], color[3], color[2], color[1], color[0] };

			byte[] data;
			String path = "/storage/emulated/0/BES/CustomerDial.bin";
			FileInputStream inputStream = null;
			try {
				inputStream = new FileInputStream(path);
				int dataSize = inputStream.available();
				data = new byte[dataSize];
				inputStream.read(data, 0, dataSize);
				inputStream.close();
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
			Log.i(TAG, path + "data: --------" + data.length);
			mPresenter.startCustomerDialTransfer(null, data, 2, 0, param);
		} else if (v.getId() == R.id.upgradetype_btn_0) {
			resetUpgradetypeView();
			upgradetype_image_0.setImageDrawable(getDrawable(R.drawable.ota_top_sele));
			SPHelper.putPreference(getApplicationContext(), Constants.OTA_UPGRADE_STYLE + curTitle, 1);
		} else if (v.getId() == R.id.upgradetype_btn_1) {
			resetUpgradetypeView();
			upgradetype_image_1.setImageDrawable(getDrawable(R.drawable.ota_top_sele));
			SPHelper.putPreference(getApplicationContext(), Constants.OTA_UPGRADE_STYLE + curTitle, 2);
		} else if (v.getId() == R.id.choose_device) {
			int scan = 0;
			if (mDeviceProtocol == DeviceProtocol.PROTOCOL_BLE) {
				scan = BluetoothConstants.Scan.SCAN_BLE;
			} else if (mDeviceProtocol == DeviceProtocol.PROTOCOL_SPP) {
				scan = BluetoothConstants.Scan.SCAN_SPP;
			} else if (mDeviceProtocol == DeviceProtocol.PROTOCOL_USB) {
				scan = BluetoothConstants.Scan.SCAN_USB;
			}
			mPresenter.pickDecice(instance, scan);
		} else if (v.getId() == R.id.connect_device) {
			isStartOta = true;
			if (view_baseoption.getVisibility() == View.GONE) {
				if (mResults.contains(MARK_FAIL) && USER_FLAG > -1) {
					ActivityUtils.showToast(R.string.ota_error_get_user_timeout);
					return;
				}
				for (int i = 0; i < mHmDevices.size(); i++) {
					if (!mResults.get(i).equals(MARK_GET_VERSION) && USER_FLAG > -1) {
						ActivityUtils.showToast(R.string.connect_failed);
						return;
					}
					if (download_ota_version == null || mFilePaths.get(i) == null || mFilePaths.get(i).length() < 3 || !(new File(mFilePaths.get(i)).exists())) {
						//ActivityUtils.showToast(R.string.pick_ota_file);
						//return;
					}
					String otaFileName = mFilePaths.get(i).substring(mFilePaths.get(i).lastIndexOf(File.separatorChar) + 1);
					//if (!otaFileName.contains(current_device_version) || !download_ota_version.contains(current_device_version)) {
						//ActivityUtils.showToast(R.string.ota_error_config_begin_start);
						//return;
					//}
				}

				view_device.setVisibility(View.GONE);
				view_versionpath.setVisibility(View.GONE);
				view_button.setVisibility(View.GONE);
				view_otaing.setVisibility(View.VISIBLE);
				view_otalog.setVisibility(View.VISIBLE);
				initOtaingView();
				initResults();

				SPHelper.putPreference(instance, BES_OTA_IS_MULTIDEVICE_UPGRADE, mHmDevices.size() > 1 ? BES_OTA_IS_MULTIDEVICE_UPGRADE : "");
				for (int i = 0; i < mHmDevices.size(); i++) {
					startOta(i);
				}
			} else {
				initResults();
				connect();
			}
		} else if (v.getId() == R.id.ota_file_tips_btn) {
			showOtaFileTipsDialog(getString(R.string.ota_file_tips));
		} else if (v.getId() == R.id.choose_file) {
			chooseFile();
		} else if (v.getId() == R.id.ota_over_btn) {
			finish();
		} else if (v.getId() == R.id.ota_check_btn) {
			if (download_ota_url == null) {
				getOtaNewVersionInfo();
			} else {
				ota_check_btn.setEnabled(false);
				downloadOtaNewVersion();
			}
		}
	}

	private void chooseFile() {
		FileUtils.fileToHex(instance, OTA_CHOOSE_FILE_PATH_RESULT - 1);
	}

	private void connect() {
		if (mServiceConfig == null || mHmDevices == null || mHmDevices.isEmpty() || BesSdkConstants.BesConnectState.BES_CONFIG_ERROR == getDeviceConnectState(mServiceConfig) || BesSdkConstants.BesConnectState.BES_CONNECT_NOTOTA == getDeviceConnectState(mServiceConfig)) {
			ActivityUtils.showToast(R.string.pleaseSelectDevice);
			return;
		}

		if (USER_FLAG != -1) {
			// current_version_details.setText(R.string.old_ota_ways_version_tips);
		} else {
			int upgradeType = (int) SPHelper.getPreference(instance, Constants.OTA_UPGRADE_STYLE + curTitle, 1);
			mServiceConfig.setImageSideSelection(upgradeType);
		}
		int upgradeType = (int) SPHelper.getPreference(instance, Constants.OTA_UPGRADE_STYLE + curTitle, 1);
		mServiceConfig.setCurUpgateType(upgradeType);
		int userType = (int) SPHelper.getPreference(instance, Constants.OTA_USER_TYPE + curTitle, 1);
		mServiceConfig.setCurUser(userType);
		boolean ackType = (boolean) SPHelper.getPreference(instance, Constants.OTA_ACK_STYLE + curTitle, false);
		if (USER_FLAG < 1) {
			mServiceConfig.setCurAckType(ackType);
		} else if (USER_FLAG == 1) {
			mServiceConfig.setIsWithoutResponse(!ackType);
		}
		String hFilePath = (String) SPHelper.getPreference(instance, Constants.OTA_HISTOTY_FILE_PATH + curTitle, "--");
		initFilePaths(hFilePath);
		for (int i = 0; i < mHmDevices.size(); i++) {
			mAdapter.add(mHmDevices.get(i).getDeviceName(), hFilePath, i);
		}
		connectDevice(0);
	}

	private void connectDevice(int index) {
		BesServiceConfig serviceConfig = new BesServiceConfig();
		serviceConfig.setDevice(mHmDevices.get(index));
		serviceConfig.setDeviceProtocol(mServiceConfig.getDeviceProtocol());
		serviceConfig.setServiceUUID(mServiceConfig.getServiceUUID());
		serviceConfig.setCharacteristicsUUID(mServiceConfig.getCharacteristicsUUID());
		serviceConfig.setDescriptorUUID(mServiceConfig.getDescriptorUUID());
		serviceConfig.setTotaConnect(mServiceConfig.getTotaConnect());
		serviceConfig.setUseTotaV2(mServiceConfig.getUseTotaV2());
		serviceConfig.setUSER_FLAG(mServiceConfig.getUSER_FLAG());
		serviceConfig.setCurUser(mServiceConfig.getCurUser());
		serviceConfig.setCurUpgateType(mServiceConfig.getCurUpgateType());
		serviceConfig.setCurAckType(mServiceConfig.getCurAckType());
		serviceConfig.setImageSideSelection(mServiceConfig.getImageSideSelection());
		serviceConfig.setIsWithoutResponse(mServiceConfig.getIsWithoutResponse());
		mPresenter.connectDevice(serviceConfig, instance, instance, index);
	}

	private void startOta(int index) {
		mPresenter.onPickOtaFile(mFilePaths.get(index), index);
		mPresenter.startOta(instance, breakPoint, index);
	}

	private void writeFile(okhttp3.Response response, String downloadFile) {
		InputStream is = null;
		FileOutputStream fos = null;
		try {
			is = response.body().byteStream();
			String path = Environment.getExternalStorageDirectory().getAbsolutePath();
			fos = new FileOutputStream(downloadFile);
			byte[] buffer = new byte[2048];
			int len;
			while ((len = is.read(buffer)) != -1) {
				fos.write(buffer, 0, len);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (is != null) {
					is.close();
				}
				if (fos != null) {
					fos.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private void getOtaNewVersionInfo() {
		get_server_ota_version.setText("Getting the newest version information.");
		download_ota_version = null;
		download_ota_version_code = 0;
		download_ota_url = null;
		download_ota_soft_name = null;
		if (current_device_version != null) {
			SharedPreferences deviceMacAddress = getApplicationContext().getSharedPreferences(PACKAGE_INFO, Context.MODE_PRIVATE);
			MsgStrAnalyzer.mMacAddress = deviceMacAddress.getString("KEY_MAC_ADDRESS_ID", MsgStrAnalyzer.mMacAddress);
			MyHttpClient.getNewWatchVersion(ota_get_version_info_callback, current_device_version);
		}
	}

	private void downloadOtaNewVersion() {
		String ota_dir = new FileUtils(instance).getOtaFilePath();
		deleteAllFilesInDirectory(ota_dir);
		if (download_ota_url != null) {
			download_ota_file_path = null;
			MyHttpClient.downloadNewestWatchVersion(ota_download_new_version_callback, download_ota_url);
		} else {
			bb.lanxing.util.Log.d("downloadOtaNewVersion", "download_ota_url is null!!! ");
		}
	}

	private void showOtaOverView(boolean success) {
		runOnUiThread(new Runnable() {
			@Override public void run() {
				mPresenter.stopOta();
				ota_over_btn.setVisibility(View.VISIBLE);
				ota_log_scrollview.setVisibility(View.GONE);
				ota_log_scrollview_short.setVisibility(View.VISIBLE);
				ota_log_text_short.setText(ota_log_text.getText());
				view_otaing_bg.setVisibility(View.GONE);
				view_otaover_bg.setVisibility(View.VISIBLE);
				if (!success) {
					ota_over_btn.setText(R.string.back);
					view_otaover_image.setImageResource(R.drawable.ota_icon_failure);
					view_otaover_text.setText(R.string.OTAFail);
					view_otaover_text.setTextColor(instance.getResources().getColor(R.color.ffff5d5d));
				}
				if (instance == null) {
					return;
				}
				boolean bleOtaAutoTest = (boolean) SPHelper.getPreference(instance, BES_BLE_OTA_AUTO_TEST, BES_BLE_OTA_AUTO_TEST_VALUE);
				if (bleOtaAutoTest) {
					try {
						Thread.sleep(300);
						startBleOtaAutoTest(success);
					} catch (InterruptedException e) {
						throw new RuntimeException(e);
					}
				}
			}
		});
	}

	private void resetAckView() {
		ack_image_0.setImageResource(R.drawable.ota_top_nor);
		ack_image_1.setImageDrawable(getDrawable(R.drawable.ota_top_nor));
	}

	private void resetUserView() {
		user_image_0.setImageResource(R.drawable.ota_top_nor);
		user_image_1.setImageDrawable(getDrawable(R.drawable.ota_top_nor));
		user_image_2.setImageDrawable(getDrawable(R.drawable.ota_top_nor));
		user_image_3.setImageDrawable(getDrawable(R.drawable.ota_top_nor));
		user_image_4.setImageDrawable(getDrawable(R.drawable.ota_top_nor));
		user_image_5.setImageDrawable(getDrawable(R.drawable.ota_top_nor));
		user_image_6.setImageDrawable(getDrawable(R.drawable.ota_top_nor));
		user_image_7.setImageDrawable(getDrawable(R.drawable.ota_top_nor));
	}

	private void resetResponseView() {
		response_image_0.setImageResource(R.drawable.ota_top_nor);
		response_image_1.setImageDrawable(getDrawable(R.drawable.ota_top_nor));
	}

	private void resetUpgradetypeView() {
		upgradetype_image_0.setImageResource(R.drawable.ota_top_nor);
		upgradetype_image_1.setImageDrawable(getDrawable(R.drawable.ota_top_nor));
	}

	@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == BluetoothConstants.Scan.REQUEST_CODE_SCAN) {
			onPickDevice(resultCode, data);
		} else if (requestCode > OTA_CHOOSE_FILE_PATH_RESULT - 2 && requestCode < OTA_CHOOSE_FILE_PATH_RESULT + 20) {
			onPickFile(resultCode, data, requestCode);
		}
	}

	@Override protected void onDestroy() {
		super.onDestroy();
		mPresenter.stopOta();
		sendBroadcast(new Intent(Constants.ACTION_CONNECT_BLE_DEVICE));
	}

	private void onPickDevice(int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			if (mDeviceProtocol == DeviceProtocol.PROTOCOL_USB) {
				mHmDevices = new ArrayList<>();
				HmDevice device = (HmDevice) data.getSerializableExtra(BluetoothConstants.Scan.BES_SCAN_RESULT);
				mHmDevices.add(device);
			} else {
				mHmDevices = (List<HmDevice>) data.getSerializableExtra(BluetoothConstants.Scan.BES_SCAN_RESULT);
			}
			device_title.setText(R.string.current_device);
			SPHelper.putPreference(instance, Constants.OTA_HISTOTY_DEVICE_NAME + curTitle, getCurDevicesNameString());
			device_name.setText(getCurDevicesName());
		}
	}

	private int getCurIndex(HmDevice hmDevice) {
		if (mDeviceProtocol == DeviceProtocol.PROTOCOL_USB) {
			return 0;
		}
		for (int i = 0; i < mHmDevices.size(); i++) {
			HmDevice device = mHmDevices.get(i);
			if (!hmDevice.getDeviceName().equals(device.getDeviceName())) {
				continue;
			}
			if (hmDevice.getPreferredProtocol() != device.getPreferredProtocol()) {
				continue;
			}
			if (hmDevice.getPreferredProtocol() == DeviceProtocol.PROTOCOL_BLE && hmDevice.getBleAddress().equals(device.getBleAddress())) {
				return i;
			}
			if (hmDevice.getPreferredProtocol() == DeviceProtocol.PROTOCOL_SPP && hmDevice.getDeviceMAC().equals(device.getDeviceMAC())) {
				return i;
			}
		}
		return 1000;
	}

	@SuppressLint("ResourceAsColor") private SpannableString getCurDevicesName() {
		SpannableString ss = new SpannableString(getCurDevicesNameString());
		int curL = 0;
		for (int i = 0; i < mHmDevices.size(); i++) {
			String deviceName = mHmDevices.get(i).getDeviceName();
			String address = mHmDevices.get(i).getPreferredProtocol() == DeviceProtocol.PROTOCOL_BLE ? mHmDevices.get(i).getBleAddress() : mHmDevices.get(i).getDeviceMAC();
			String addStr = deviceName + "(" + address + ")";
			if (mDeviceProtocol == DeviceProtocol.PROTOCOL_USB) {
				addStr = deviceName;
			}
			mServiceConfig.setDevice(mHmDevices.get(i));
			if (getDeviceConnectState(mServiceConfig) == BesSdkConstants.BesConnectState.BES_CONNECT) {
				ss.setSpan(new ForegroundColorSpan(Color.rgb(103, 200, 77)), curL, addStr.length() + curL, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
			}
			curL += (addStr.length() + 3);
		}
		return ss;
	}

	private String getCurDevicesNameString() {
		String deviceNames = "";
		for (int i = 0; i < mHmDevices.size(); i++) {
			String deviceName = mHmDevices.get(i).getDeviceName();
			String address = mHmDevices.get(i).getPreferredProtocol() == DeviceProtocol.PROTOCOL_BLE ? mHmDevices.get(i).getBleAddress() : mHmDevices.get(i).getDeviceMAC();
			String addStr = deviceName + "(" + address + ")";
			if (mDeviceProtocol == DeviceProtocol.PROTOCOL_USB) {
				addStr = deviceName;
			}
			deviceNames = i == 0 ? addStr : deviceNames + ", " + "\n" + addStr;
		}
		return deviceNames;
	}

	public BesSdkConstants.BesConnectState getDeviceConnectState(BesServiceConfig serviceConfig) {
		return BTService.getDeviceConnectState(instance, serviceConfig);
	}

	private void onPickFile(int resultCode, Intent data, int requestCode) {
		breakPoint = 0;
		if (resultCode == RESULT_OK) {
			String filePath;
			boolean internalFileAccess = (boolean) SPHelper.getPreference(instance, BES_KEY_USE_INTERNAL_FILE_ACCESS, BES_USE_INTERNAL_FILE_ACCESS);
			internalFileAccess = true;
			if (internalFileAccess) {
				filePath = data.getStringExtra(BES_KEY_USE_INTERNAL_FILE_ACCESS_CHOOSE_FILE);
			} else {
				filePath = data.getStringExtra(FilePickerActivity.RESULT_FILE_PATH);
			}
			LOG(TAG, "onPickFile:----" + filePath);
			int index = requestCode - OTA_CHOOSE_FILE_PATH_RESULT;
			LOG(TAG, "onPickFile:" + index);
			if (index < 0) {
				SPHelper.putPreference(instance, Constants.OTA_HISTOTY_FILE_PATH + curTitle, filePath);
				initFilePaths(filePath);
				mAdapter.clear();
				for (int i = 0; i < mHmDevices.size(); i++) {
					mAdapter.add(mHmDevices.get(i).getDeviceName(), filePath, i);
				}
			} else {
				if (mFilePaths.size() > index) {
					mFilePaths.remove(index);
				}
				mFilePaths.add(index, filePath);
				mAdapter.add(mHmDevices.get(index).getDeviceName(), filePath, index);
			}
		}
	}

	private void onPickServerFile() {
		LOG(TAG, "onPickServerFile:----" + download_ota_file_path);
		breakPoint = 0;
		int index = 0;
		if (mFilePaths.size() > index) {
			mFilePaths.remove(index);
		}
		mFilePaths.add(index, download_ota_file_path);
		mAdapter.add(mHmDevices.get(index).getDeviceName(), download_ota_file_path, index);
	}

	@Override public void onTotaConnectState(boolean state, HmDevice hmDevice) {
		if (!state) {
			mResults.remove(getCurIndex(hmDevice));
			mResults.add(getCurIndex(hmDevice), MARK_FAIL);
		}
	}

	@Override public void onErrorMessage(int msg, HmDevice hmDevice) {
		runOnUiThread(() -> {
			if (!isStartOta) {
				ActivityUtils.showToast(R.string.pleaseSelectDevice);
				return;
			}
			Log.i(TAG, "onErrorMessage: ---------" + hmDevice);
			switch (msg) {
				case OTA_START_OTA_ERROR:
					refreshUI(R.string.ota_error_config_before_start);
					break;
				case OTA_CMD_SELECT_SIDE_ERROR:
					refreshUI(R.string.ota_error_choose_side);
					break;
				case OTA_CMD_SEND_CONFIGURE_ERROR:
					refreshUI(R.string.ota_error_config_begin_start);
					break;
				case OTA_CMD_CRC_CHECK_PACKAGE_ERROR:
					refreshUI(R.string.ota_error_percent_crc);
					break;
				case OTA_CMD_WHOLE_CRC_CHECK_ERROR:
					refreshUI(R.string.ota_error_whole_crc);
					break;
				case OTA_CMD_IMAGE_OVER_CONFIRM_ERROR:
					refreshUI(R.string.ota_error_whole_image);
					break;
				case OTA_CMD_SET_OAT_USER_ERROR:
					refreshUI(R.string.ota_error_set_user);
					break;
				case OTA_START_DEVICE_LOW_BATTERY_ERROR:
					dialogDismiss();
					ActivityUtils.showToast("OTA Fail: Please check the battery");
					return;
				case MSG_GET_PROTOCOL_VERSION_TIME_OUT:
					refreshUI(R.string.ota_error_get_user_timeout);
					ActivityUtils.showToast(R.string.ota_error_get_user_timeout);
					break;
				case MSG_GET_VERSION_TIME_OUT:
					refreshUI(R.string.ota_error_get_version_timeout);
					ActivityUtils.showToast(R.string.ota_error_get_version_timeout);
					break;
				default:
					break;
			}
			Log.i(TAG, "mResults0: ------" + mResults);
			mResults.remove(getCurIndex(hmDevice));
			mResults.add(getCurIndex(hmDevice), MARK_FAIL);
			reloadOtaingTextColor(getCurIndex(hmDevice), false);
			if (checkCurResults() == CurResultsState.BES_OVER_ALL_FAIL || mHmDevices.size() == 1) {
				showOtaOverView(false);
				return;
			}
			if (view_versionpath.getVisibility() == View.GONE) {
				return;
			}
			if (getCurIndex(hmDevice) + 1 < mHmDevices.size()) {
				connectDevice(getCurIndex(hmDevice) + 1);
			} else {
				dialogDismiss();
			}
		});
	}

	@Override public void onStateChangedMessage(int msg, String msgStr, HmDevice hmDevice) {
		Log.i(TAG, "onStateChangedMessage: --------" + msg + "----" + msgStr);
		if (null == instance) {
			return;
		}
		runOnUiThread(() -> {
			// Customer dial
			if (msg == OP_TOTA_WRITE_FLASH_PROCESS) {
				Log.i(TAG, "OP_TOTA_WRITE_FLASH_PROCESS: --------" + Float.valueOf(msgStr).intValue());
				// transfer_percent.setText(msgStr + "%");
				// transfer_progress.setProgress(Float.valueOf(msgStr).intValue());
			} else if (msg == OP_TOTA_WRITE_FLASH_WHOLE_CHECK_RESULT_OK) {
				// showToast(R.string.OTASuccess);
				// start_transfer.setEnabled(false);
				// start_transfer.setBackground(getDrawable(R.drawable.ota_button_bg_press));
				// start_transfer.setText(getString(R.string.start_transfer_tips));
				mOtaUpdateSuccStatus = OP_TOTA_WRITE_FLASH_WHOLE_CHECK_RESULT_OK;
				// mPresenter.disconnectCustomerDialService();
			} else if (msg == OP_TOTA_WRITE_FLASH_WHOLE_CHECK_RESULT_FAIL) {
				// showToast(R.string.OTAFail);
			} else if (msg == CUSTOMER_DIAL_LOG_INFO) {
				// String str = logV.getText() + "\n" + msgStr;
				// logV.setText(str);
			} else if (msg == CUSTOMER_DIAL_GET_FLASH_ADDRESS_RESULT_FAIL) {
				// showToast(R.string.flash_address_error);
			}

			switch (msg) {
				case BES_CONNECT_SUCCESS:
					if (!isStartOta) {
						return;
					}
					if (view_otaing.getVisibility() == View.VISIBLE) {
						return;
					}
					if (USER_FLAG == -1) {
						device_version.setText("");
					}
					device_name.setText(getCurDevicesName());
					view_baseoption.setVisibility(View.GONE);
					act_otaui_bg.setBackground(getResources().getDrawable(R.mipmap.bes_bg_white));
					view_versionpath.setVisibility(View.VISIBLE);
					choose_device.setVisibility(View.INVISIBLE);
					connect_device.setText(R.string.start_ota);
					break;
				case BES_CONNECT_ERROR:
					dialogDismiss();
					boolean isOtaing = false;
					for (int i = 0; i < mProgresses.size(); i++) {
						if (mProgresses.get(i) > 0) {
							isOtaing = true;
						}
					}
					if (isOtaing) {
						refreshUI(R.string.connect_failed);
						showOtaOverView(false);
						return;
					}
					connect_device.setVisibility(View.VISIBLE);
					ActivityUtils.showToast(R.string.connect_failed);
					refreshUI(R.string.connect_failed);
					if (view_versionpath.getVisibility() == View.GONE && mServiceConfig.getDeviceProtocol() != DeviceProtocol.PROTOCOL_USB) {
						return;
					}
					if (getCurIndex(hmDevice) + 1 < mHmDevices.size()) {
						connectDevice(getCurIndex(hmDevice) + 1);
					} else {
						dialogDismiss();
					}
					boolean bleOtaAutoTest0 = (boolean) SPHelper.getPreference(instance, BES_BLE_OTA_AUTO_TEST, BES_BLE_OTA_AUTO_TEST_VALUE);
					if (bleOtaAutoTest0) {
						showOtaOverView(false);
					}
					break;
				case OTA_CMD_GET_HW_INFO:
					mResults.remove(getCurIndex(hmDevice));
					mResults.add(getCurIndex(hmDevice), MARK_GET_VERSION);
					if (getCurIndex(hmDevice) + 1 < mHmDevices.size()) {
						connectDevice(getCurIndex(hmDevice) + 1);
					} else {
						dialogDismiss();
					}
					// device_version.setText(device_version.getText().toString().equals(instance.getString(R.string.old_ota_ways_version_tips))
					// ? hmDevice.getDeviceName() + " " + msgStr : device_version.getText() + "\n" +
					// hmDevice.getDeviceName() + " " + msgStr);
					current_device_version = msgStr;
					device_version.setText(current_device_version);

					boolean bleOtaAutoTest = (boolean) SPHelper.getPreference(instance, BES_BLE_OTA_AUTO_TEST, BES_BLE_OTA_AUTO_TEST_VALUE);
					if (bleOtaAutoTest) {
						autoStartOta();
					}
					break;
				case OTA_CMD_GET_PROTOCOL_VERSION:
					loadinganim();
					refreshUI(R.string.ota_get_version_success);
					break;
				case OTA_CMD_SET_OAT_USER_OK:
					refreshUI(R.string.ota_set_user_success);
					break;
				case OTA_CMD_SET_UPGRADE_TYPE_NORMAL:
					// upgradechoose.check(R.id.slow_mod);
					refreshUI(R.string.ota_set_upgrade_type_slow);
					break;
				case OTA_CMD_SET_UPGRADE_TYPE_FAST:
					// upgradechoose.check(R.id.fast_mod);
					refreshUI(R.string.ota_set_upgrade_type_fast);
					break;
				case OTA_CMD_ROLESWITCH_GET_RANDOMID:
					refreshUI("role switch random id:" + msgStr);
					break;
				case OTA_CMD_SELECT_SIDE_OK:
					refreshUI("select side ok");
					break;
				case OTA_CMD_BREAKPOINT_CHECK_80:
					// show config
					refreshUI(R.string.ota_no_breakpoint_resume);
					getSupportFragmentManager().executePendingTransactions();
					//mOtaConfigDialog.show(getSupportFragmentManager(), "OTA_CONFIG_TAG");
					mPresenter.startOta(instance, breakPoint, 0);
					break;
				case OTA_CMD_BREAKPOINT_CHECK:
					refreshUI(R.string.ota_breakpoint_resume);
					break;
				case OTA_CMD_SEND_CONFIGURE_OK:
					refreshUI(R.string.ota_start);
					break;
				case OTA_CMD_DISCONNECT:
					refreshUI(R.string.ota_disconnect_success);
					break;
				case OTA_CMD_ROLESWITCH_COMPLETE:
					refreshUI("receive OTA_CMD_ROLESWITCH_COMPLETE");
					break;
				case OTA_CMD_WHOLE_CRC_CHECK_OK:
					refreshUI(R.string.ota_whole_crc_success);
					break;
				case OTA_CMD_CRC_CHECK_PACKAGE_ERROR:
					refreshUI(R.string.ota_percent_crc_error_resend);
					break;
				case OTA_SEND_DATA_PROGRESS:
					reloadOtaingView(hmDevice.getDeviceName(), msgStr, getCurIndex(hmDevice));
					break;
				case MSG_GET_RANDOMID_TIME_OUT:
					refreshUI("get 'random id' timeout, next step");
					break;
				case MSG_GET_UPGRATE_TYPE_TIME_OUT:
					refreshUI("set 'upgratetype' timeout, next step");
					break;
				case OTA_CMD_CRC_CHECK_PACKAGE_OK:
					refreshUI(msgStr);
					break;
				default:
					break;
			}
		});
	}

	@Override public void onSuccessMessage(int msg, HmDevice hmDevice) {
		boolean bleOtaAutoTest = (boolean) SPHelper.getPreference(instance, BES_BLE_OTA_AUTO_TEST, BES_BLE_OTA_AUTO_TEST_VALUE);
		if (bleOtaAutoTest == false) {
			mTasksView = null;
		}
		mResults.remove(getCurIndex(hmDevice));
		mResults.add(getCurIndex(hmDevice), MARK_SUCCESS);
		reloadOtaingTextColor(getCurIndex(hmDevice), true);
		if (checkCurResults() == CurResultsState.BES_OVER_ALL_SUCCESS || mHmDevices.size() == 1) {
			showOtaOverView(true);
		}
	}

	private void refreshUI(String str) {
		String old = ota_log_text.getText().toString();
		ota_log_text.setText(old + "\n" + getCurrentTime() + "  " + str);
	}

	private void refreshUI(int rString) {
		String old = ota_log_text.getText().toString();
		ota_log_text.setText(old + "\n" + getCurrentTime() + "  " + getString(rString));
	}

	private String getCurrentTime() {
		SimpleDateFormat formatter = new SimpleDateFormat("dd:HH:mm:ss:sss");
		Date curDate = new Date(System.currentTimeMillis());
		return formatter.format(curDate);
	}

	@Override public void onOTAStatusChanged(OTAStatus newStatus, HmDevice hmDevice) {
		LOG(TAG, "onOTAStatusChanged-------");
	}

	@Override public void onOTAProgressChanged(int progress, HmDevice hmDevice) {
		int index = getCurIndex(hmDevice);
		mProgresses.remove(index);
		mProgresses.add(index, progress);
		int result = 0;
		for (int i = 0; i < mHmDevices.size(); i++) {
			result = result + mProgresses.get(i);
		}
		mTasksView.setProgress(result / mHmDevices.size());
	}

	public void startBleOtaAutoTest(boolean isLastSuccess) {
		LOG(TAG, "startBleOtaAutoTest-------");
		ota_log_text.setText("");
		dialogDismiss();
		mTasksView.setProgress(0);
		text_percent0.setTextColor(getResources().getColor(R.color.ff087ec2));
		ota_over_btn.setVisibility(View.GONE);
		ota_log_scrollview.setVisibility(View.VISIBLE);
		ota_log_scrollview_short.setVisibility(View.GONE);
		view_otaing_bg.setVisibility(View.VISIBLE);
		view_otaover_bg.setVisibility(View.GONE);

		view_device.setVisibility(View.VISIBLE);
		view_baseoption.setVisibility(View.VISIBLE);
		view_button.setVisibility(View.VISIBLE);
		choose_device.setVisibility(View.VISIBLE);
		connect_device.setText(R.string.connect_device);

		view_otaing.setVisibility(View.GONE);
		view_versionpath.setVisibility(View.GONE);
		view_otalog.setVisibility(View.GONE);

		if (isLastSuccess) {
			String oldPath = (String) SPHelper.getPreference(instance, Constants.OTA_HISTOTY_FILE_PATH + curTitle, "--");
			LOG(TAG, "oldPath-------" + oldPath);
			if (oldPath.contains(BES_BLE_OTA_AUTO_TEST_BIN_NAME_MARK)) {
				String newPath = oldPath.replace(BES_BLE_OTA_AUTO_TEST_BIN_NAME_MARK, "");
				SPHelper.putPreference(instance, Constants.OTA_HISTOTY_FILE_PATH + curTitle, newPath);
			} else {
				String newPath = oldPath.replace(".bin", BES_BLE_OTA_AUTO_TEST_BIN_NAME_MARK + ".bin");
				if (new File(newPath).exists()) {
					SPHelper.putPreference(instance, Constants.OTA_HISTOTY_FILE_PATH + curTitle, newPath);
				}
			}
			LOG(TAG, "newPath-------" + (String) SPHelper.getPreference(instance, Constants.OTA_HISTOTY_FILE_PATH + curTitle, "--"));
		}
		new Thread(new Runnable() {
			@Override public void run() {
				try {
					if (isLastSuccess) {
						int bleAutoTestInteval = (int) SPHelper.getPreference(instance, BesSdkConstants.BES_BLE_OTA_AUTO_TEST_INTERVAL, BesSdkConstants.BES_BLE_OTA_AUTO_TEST_INTERVAL_VALUE);
						Thread.sleep(1000 * 60 * bleAutoTestInteval);
					} else {
						Thread.sleep(1000 * 20);
					}
					startScanDevice();
				} catch (InterruptedException e) {
					throw new RuntimeException(e);
				}
			}
		}).start();
	}

	@SuppressLint("MissingPermission") public void startScanDevice() {
		BluetoothAdapter mBluetoothAdapter = BtHeleper.getBluetoothAdapter(instance);
		mLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
		mLeScanner.startScan(null, new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build(), mCallback);
	}

	public void autoStartOta() {
		if (view_baseoption.getVisibility() == View.GONE) {
			if (mResults.contains(MARK_FAIL) && USER_FLAG > -1) {
				ActivityUtils.showToast(R.string.ota_error_get_user_timeout);
				return;
			}
			for (int i = 0; i < mHmDevices.size(); i++) {
				if (!mResults.get(i).equals(MARK_GET_VERSION) && USER_FLAG > -1) {
					ActivityUtils.showToast(R.string.connect_failed);
					return;
				}
				if (download_ota_version == null || mFilePaths.get(i) == null || mFilePaths.get(i).length() < 3 || !(new File(mFilePaths.get(i)).exists())) {
					ActivityUtils.showToast(R.string.pick_ota_file);
					return;
				}
				String otaFileName = mFilePaths.get(i).substring(mFilePaths.get(i).lastIndexOf(File.separatorChar) + 1);
				if (!otaFileName.contains(current_device_version) || !download_ota_version.contains(current_device_version)) {
					ActivityUtils.showToast(R.string.ota_error_config_begin_start);
					return;
				}
			}
			view_device.setVisibility(View.GONE);
			view_versionpath.setVisibility(View.GONE);
			view_button.setVisibility(View.GONE);
			view_otaing.setVisibility(View.VISIBLE);
			view_otalog.setVisibility(View.VISIBLE);
			initOtaingView();
			initResults();
			SPHelper.putPreference(instance, BES_OTA_IS_MULTIDEVICE_UPGRADE, mHmDevices.size() > 1 ? BES_OTA_IS_MULTIDEVICE_UPGRADE : "");
			for (int i = 0; i < mHmDevices.size(); i++) {
				startOta(i);
			}
		}
	}

	public void LOG(String TAG, String msg) {
		if (instance == null) {
			return;
		}
		String saveLogName = (String) SPHelper.getPreference(instance, BesSdkConstants.BES_SAVE_LOG_NAME, "");
		boolean saveLog = (boolean) SPHelper.getPreference(instance, BesSdkConstants.BES_SAVE_LOG_KEY, BesSdkConstants.BES_SAVE_LOG_VALUE);
		if (saveLog) {
			if (saveLogName.equals(BES_SAVE_LOG_OTA)) {
				// LogUtils.writeForOTA(TAG, msg, saveLogName);
			} else if (saveLogName.length() > 0) {
				// LogUtils.writeForLOG(TAG, msg, saveLogName);
			}
		}
	}

	private enum CurResultsState {
		BES_UPGRADING, BES_UPGRADING_HAS_FAIL, BES_OVER_HAS_FAIL, BES_OVER_ALL_SUCCESS, BES_OVER_ALL_FAIL
	}

	private final android.bluetooth.le.ScanCallback mCallback = new android.bluetooth.le.ScanCallback() {
		@Override public void onScanFailed(int errorCode) {
			super.onScanFailed(errorCode);
			LOG(TAG, "onScanFailed: ---------fail");
			startScanDevice();
		}

		@SuppressLint("MissingPermission") @Override public void onScanResult(int callbackType, ScanResult result) {
			String address = mHmDevices.get(0).getBleAddress();
			if (result.getDevice().getAddress().equals(address)) {
				mLeScanner.stopScan(mCallback);
				mHmDevices = new ArrayList<>();
				HmDevice device = new HmDevice();
				device.setDeviceName(result.getDevice().getName());
				device.setBleAddress(address);
				device.setPreferredProtocol(DeviceProtocol.PROTOCOL_BLE);
				mHmDevices.add(device);
				initResults();
				connect();
			}
		}
	};

	private void dialogDismiss() {
		if (null != loadingDialog) {
			loadingDialog.dismiss();
		}
	}
}
